<template>
  <div class="merchantAdd">
    <el-form
      ref="merchantFormRef"
      :model="merchantForm"
      :rules="merchantRules"
      label-width="auto">

      <el-card style="margin-bottom: 15px;">
        <template #header>基本信息</template>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="店铺名称" prop="name">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.name"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="店铺中文名" prop="chineseName">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.chineseName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="店铺印尼名" prop="indonesiaName">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.indonesiaName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="简介" prop="snapshot">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.snapshot"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.remark"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业时间" prop="businessTime">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.businessTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                :autosize="{ minRows: 2, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.phone"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contacts">
              <el-input
                :autosize="{ minRows: 2, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.contacts"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标签" prop="tags">
              <el-input-tag
                v-model="merchantForm.tags"
                placeholder="请输入回车"
                draggable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属行业" prop="categoryList">
              <el-cascader
                style="width: 100%"
                v-model="merchantForm.categoryList"
                :options="categoryList"
                :props="{value: 'id', label: 'name', expandTrigger: 'hover'}"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="均价" prop="averagePrice">
              <el-input v-model="merchantForm.averagePrice"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="店铺状态" prop="status">
              <el-radio-group v-model="merchantForm.status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否入驻" prop="settled">
              <el-radio-group v-model="merchantForm.settled">
                <el-radio :value="0">未入驻</el-radio>
                <el-radio :value="1">已入驻</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入驻时间" prop="settledTime">
              <el-date-picker
                v-model="merchantForm.settledTime"
                type="datetime"
                placeholder="请选择"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="YYYY/MM/DD hh:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card style="margin-bottom: 15px;">
        <template #header>位置信息</template>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商圈详细地址" prop="address">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.address"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="中文地址" prop="chineseAddress">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.chineseAddress"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="印尼语地址" prop="indonesiaAddress">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.indonesiaAddress"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="谷歌地址" prop="addressGoogle">
              <el-input
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="merchantForm.addressGoogle"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="经度" prop="lat">
              <el-input v-model="merchantForm.lat"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="纬度" prop="lon">
              <el-input v-model="merchantForm.lon"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card style="margin-bottom: 15px;">
        <template #header>图片信息</template>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="商家logo" prop="logoFile">
              <el-upload
                class="avatar-uploader"
                :accept="accept"
                ref="upload1"
                :action="uploadUrl"
                :headers="headers"
                :show-file-list="false"
                :on-success="(res) => handlePicSuccess(res, 'logoFile')">
                <img
                  v-if="merchantForm.logoFile && merchantForm.logoFile.hasOwnProperty('url')"
                  :src="merchantForm.logoFile.url"
                  class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="商家主图" prop="picFile">
              <el-upload
                class="avatar-uploader"
                :accept="accept"
                ref="upload2"
                :action="uploadUrl"
                :headers="headers"
                :show-file-list="false"
                :on-success="(res) => handlePicSuccess(res, 'picFile')">
                <img
                  v-if="merchantForm.picFile && merchantForm.picFile.hasOwnProperty('url')"
                  :src="merchantForm.picFile.url"
                  class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="商家环境图" prop="environmentPicFile">
              <el-upload
                :accept="accept"
                :action="uploadUrl"
                :headers="headers"
                list-type="picture-card"
                :file-list="merchantForm.environmentPicFile"
                :on-success="handleEnvironmentPicSuccess"
                :on-remove="handleEnvironmentPicRemove"
                :on-preview="handlePictureCardPreview"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <el-dialog v-model="dialogVisible">
                <el-image w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card style="margin-bottom: 15px;" v-if="merchantForm.id">
        <template #header>
          <el-space>
            <span>经营数据</span>
            <el-icon><PieChart /></el-icon>
          </el-space>
        </template>
        <el-descriptions
          border
          size="small"
          :label-width="100"
          :column="4">
          <el-descriptions-item label="评分">{{ merchantForm.score || '-' }}</el-descriptions-item>
          <el-descriptions-item label="评论数量">{{ merchantForm.scoreNum || '-' }}</el-descriptions-item>
          <el-descriptions-item label="点赞数量">{{ merchantForm.good || '-' }}</el-descriptions-item>
          <el-descriptions-item label="反对数量">{{ merchantForm.bad || '-' }}</el-descriptions-item>
          <el-descriptions-item label="口味评价">{{ merchantForm.taste || '-' }}</el-descriptions-item>
          <el-descriptions-item label="服务评价">{{ merchantForm.service || '-' }}</el-descriptions-item>
          <el-descriptions-item label="性价比评价">{{ merchantForm.costEffectiveness || '-' }}</el-descriptions-item>
          <el-descriptions-item label="环境评价">{{ merchantForm.environment || '-' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      <div style="display: flex; justify-content: center;">
        <el-form-item>
          <el-button size="large" type="primary" @click="handleSubmit">保存</el-button>
          <el-button size="large"  @click="handleCancel">返回</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script setup>
import { getToken } from "@/utils/auth";
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import HiTitle from "@/components/HiTitle/index.vue";
import { getMerchant, addMerchant, updateMerchant } from "@/api/merchant/index.js";
import { listCategory } from "@/api/category/index.js";

// 上传的图片服务器地址
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload");
const headers = ref({ Authorization: "Bearer " + getToken() });
const accept = ref("image/png, image/jpeg, image/jpg");

//获取商家分类
onMounted(() => { getCategoryList() });
const categoryList = ref([])
const getCategoryList = () => {
  listCategory().then(res => {
    const { data } = res;
    categoryList.value = data;
  })
}

//表单相关
const merchantFormRef = ref(null);
const merchantForm = reactive({
  id: undefined,
  name: '',               //店铺名称
  chineseName: '',        //店铺中文名
  indonesiaName: '',      //店铺印尼名
  snapshot: '',           //简介
  remark: '',             //备注
  businessTime: '',       //营业时间
  phone: '',              //联系电话
  contacts: '',           //联系人
  tags: [],               //标签
  settled: 0,            //是否入驻（0-未入驻，1入驻）
  settledTime: '',        //入驻时间
  categoryList: [],       //所属行业
  status: '0',            //店铺状态（0正常 1停用）
  averagePrice: '',       //均价

  lat: '',                //经度
  lon: '',                //纬度
  address: '',            //商圈详细地址
  chineseAddress: '',     //中文地址
  indonesiaAddress: '',   //印尼语地址
  addressGoogle: '',      //谷歌地址

  logoFile: null,
  picFile: null,
  environmentPicFile: [], //展示轮播图

  score: '',               //评分
  scoreNum: '',            //评论数量
  good: '',                //点赞数量
  bad: '',                 //反对数量
  taste: '',               //口味评价
  service: '',             //服务评价
  costEffectiveness: '',   //性价比评价
  environment: '',         //环境评价
})
const merchantRules = reactive({
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
  ],
  chineseName: [
    { required: true, message: '请输入店铺中文名', trigger: 'blur' },
  ],
  indonesiaName: [
    { required: true, message: '请输入店铺印尼名', trigger: 'blur' },
  ],
  snapshot: [
    { required: true, message: '请输入简介', trigger: 'blur' },
  ],
  settledTime: [
    { required: true, message: '请输入入驻时间', trigger: 'blur' },
  ],
  categoryList: [
    { required: true, message: '请选择所属行业', trigger: 'blur' },
  ],
  tags: [
    { required: true, message: '请输入标签', trigger: 'blur' },
  ],
  logoFile: [
    { required: true, message: '请上传商家logo', trigger: 'blur' },
  ],
  picFile: [
    { required: true, message: '请上传商家主图', trigger: 'blur' },
  ],
  environmentPicFile: [
    { required: true, message: '请上传商家环境图', trigger: 'blur' },
  ],
  lat: [
    { required: true, message: '请输入经度', trigger: 'blur' },
  ],
  lon: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
  ],
  address: [
    { required: true, message: '请输入商圈详细地址', trigger: 'blur' },
  ],
  chineseAddress: [
    { required: true, message: '请输入中文地址', trigger: 'blur' },
  ],
  indonesiaAddress: [
    { required: true, message: '请输入印尼语地址', trigger: 'blur' },
  ],
  addressGoogle: [
    { required: true, message: '请输入谷歌地址', trigger: 'blur' },
  ],
})

//上传商家logo、主图
const handlePicSuccess = (response, fieldName) => {
  const { id, fileName, oldName, url } = response;
  merchantForm[fieldName] = { id, name: fileName, url, route: oldName }
}

//上传商家环境图
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleEnvironmentPicSuccess = (response, uploadFile) => {
  const { id, fileName, oldName, url } = response;
  merchantForm.environmentPicFile.push({ id, name: fileName, url, route: oldName });
}
const handleEnvironmentPicRemove = (uploadFile, uploadFiles) => {
  let id = undefined;
  if(uploadFile.hasOwnProperty('response')) {
    id = uploadFile.response.id;
  }else {
    id = uploadFile.id;
  }
  const index = merchantForm.environmentPicFile.findIndex(item => item.id === id);
  if (index !== -1) {
    merchantForm.environmentPicFile.splice(index, 1);
  } else {
    ElMessage.error('删除失败');
  }
}
const handlePictureCardPreview = (uploadFile) => {
  const { url } = uploadFile;
  dialogImageUrl.value = url;
  dialogVisible.value = true
}

//修改商家
const route = useRoute();
const { id } = route.query;
onMounted(() => { initData() })
const initData = () => {
  if (id) {
    getMerchant(id).then(response => {
      let { data } = response;
      data.tags = data.tags.split(',');
      data.categoryList = data.categoryList ? [data.categoryList.id, data.categoryList.children[0].id] : [];
      Object.assign(merchantForm, data);
    })
  }
}

//保存或更新商家
const handleSubmit = async () => {
  if (!merchantFormRef.value) return; // 确保 ruleFormRef 已正确初始化
  try {
    await merchantFormRef.value.validate(); // 正确调用 validate 方法
    //参数组合
    const { tags, categoryList } = merchantForm;
    const params = {
      ...merchantForm,
      tags: tags.length ? tags.join(",") : '',
      categoryList: {
        id: categoryList[0],
        parentId: 0,
        children: [{
          id: categoryList[1],
          parentId: categoryList[0],
        }]
      },
    }
    //更新或保存
    if (merchantForm.id) {
      await updateMerchant(params)
      ElMessage.success('编辑成功');
      handleCancel();
    }else {
      await addMerchant(params)
      ElMessage.success('新增成功');
      handleCancel();
    }
  } catch (error) {
    console.error('验证失败:', error);
  }
}

const router = useRouter()
const handleCancel = () => {
  router.go(-1)
}

</script>
<style lang="scss" scoped>
div.merchantAdd {
  width: 100%;
  padding: 15px;
  background: #f3f4f7;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  text-align: center;
}
</style>
